package com.detrum.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;

import com.detrum.DownloadReceiver;
import com.detrum.base.BaseStatic;
import com.detrum.base.R;
import com.detrum.utils.LogUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


import static com.detrum.base.BaseStatic.appNetCode;
import static com.detrum.base.BaseStatic.path;

public class DownloadService extends Service {
    private String TAG="DownloadService";
    private String name;
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private DownloadReceiver receiver = new DownloadReceiver();
    private boolean isenable;
    private int notifyId=3;

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter=new IntentFilter();
        filter.addAction("download");
        registerReceiver(receiver,filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(BaseStatic.appNetPath==null){
            stopSelf(startId);
            return Service.START_STICKY_COMPATIBILITY;
        }
        String[]strs = BaseStatic.appNetPath.split("/");
        name = strs[strs.length-1];

        isenable = NotificationManagerCompat.from(this).areNotificationsEnabled();
        if(isenable){
            builder = new NotificationCompat.Builder(this.getApplicationContext());
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle(name);
            builder.setOngoing(true);
            builder.setPriority(Notification.PRIORITY_DEFAULT);
            manager.notify(notifyId,builder.build());
        }
        LogUtils.i("isenable = "+isenable);

        File file1=new File(path,name);
        if(file1.exists()&&file1.length()!=0){
            int code=apkInfo(file1.getAbsolutePath(),DownloadService.this);
            LogUtils.e("apkcode = "+code+"  netCode = "+appNetCode);
            if(code<BaseStatic.appNetCode){
                file1.delete();
                myTask=new MyTask();
                myTask.execute();
            }else{
                Intent intent1=new Intent("download");
                intent1.putExtra("path",file1.getPath());
                sendBroadcast(intent1);
                if(manager!=null){
                    manager.cancel(notifyId);
                }
            }
        }else{
            myTask=new MyTask();
            myTask.execute();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    private MyTask myTask;
    private File file,fileTemp;
    private int length;//文件长度
    class MyTask extends AsyncTask<Void,Integer,File> {

        @Override
        protected void onPostExecute(final File s) {
            super.onPostExecute(s);
            //下载完成
            if(s==null){
                Intent intent1=new Intent("download");
                intent1.putExtra("verify","fail");
                sendBroadcast(intent1);
                return;
            }
            if(s.length()==0){
                s.delete();
            }else{
                Intent intent1=new Intent("download");
                intent1.putExtra("path",s.getPath());
                sendBroadcast(intent1);
            }
            if(manager!=null){
                manager.cancel(notifyId);
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
        }

        @Override
        protected File doInBackground(Void... params) {
            try {
                File file1=new File(path);
                if(!file1.exists()){
                    file1.mkdirs();
                }
                fileTemp=new File(path,name+".det");
                FileOutputStream fos=new FileOutputStream(fileTemp);
                LogUtils.i("appNetPath = "+BaseStatic.appNetPath);
                URL url=new URL(BaseStatic.appNetPath);
                LogUtils.i("url = "+url);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                length = httpURLConnection.getContentLength();
                if(length!=BaseStatic.appNetLength){
                    LogUtils.i("length = "+length+"  appNetLength = "+BaseStatic.appNetLength);
                    return null;
                }

                InputStream is=httpURLConnection.getInputStream();

                int x=0,y=0;
                byte[] b=new byte[10240];
                while ((x=is.read(b))!=-1){
                    fos.write(b,0,x);
                    y+=x;
                    if(isenable){
                        builder.setProgress(length,y,false);
                        builder.setContentText("下载"+y*100/length+"%");
                        manager.notify(notifyId,builder.build());
                    }else{
                        Intent intent2=new Intent("download");
                        intent2.putExtra("length",length);
                        intent2.putExtra("progress",y);
                        sendBroadcast(intent2);
                    }
                }
                fos.flush();
                if(is!=null){
                    is.close();
                }
                if(fos!=null){
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            if(fileTemp.length()==length){
                file = new File(path,name);
                fileTemp.renameTo(file);
                String md5 = checkMd5(file);
                LogUtils.e("md5 = "+md5+"  appVerify = "+BaseStatic.appNetVerify);
                if(!md5.equals(BaseStatic.appNetVerify)){
                    file.delete();
                    return null;
                }
            }else{
                fileTemp.delete();
            }

            return file;
        }

    }

    private String checkMd5(File file) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);
            byte[]data =new byte[10240];
            int len;
            while ((len = fis.read(data,0,10240))!=-1){
                md.update(data,0,len);
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, md.digest());
        return bigInt.toString(16);
    }

    /**
     * 获取apk包的信息：版本号，名称，图标等
     * @param absPath apk包的绝对路径
     * @param context
     */
    public int apkInfo(String absPath, Context context) {
        int code=0;
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
        /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */
            appInfo.sourceDir = absPath;
            appInfo.publicSourceDir = absPath;
            String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
            String packageName = appInfo.packageName; // 得到包名
            String version = pkgInfo.versionName; // 得到版本信息
            code=pkgInfo.versionCode;//得到code信息--判断是否比当前大
        /* icon1和icon2其实是一样的 */
            Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息
            Drawable icon2 = appInfo.loadIcon(pm);
            String pkgInfoStr = String.format("PackageName:%s, Vesion: %s, AppName: %s", packageName, version, appName);
        }
        return code;
    }
}
